package ocg.common.re.jdbc;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by chenbo on 2018/3/1.
 * 数据库操作级别类型
 */
public class JdbcService {

    Logger logger = LogManager.getLogger ( this.getClass () );

    private Connection connection;
    private ResultSet resultSet;

    public JdbcService( Connection connection ) {
        this.connection = connection;
    }

    /**
     * 查询操作，返回结果集 ResultSet
     * @param sql
     * @return
     */
    public ResultSet getResultSet( String sql )  {


        Statement statement = null ;
        try {
            if ( connection != null ){
                statement = connection.createStatement ();
                logger.info ( "sql : " + sql );
                resultSet = statement.executeQuery ( sql );
            }else {
                logger.error ("connection is " + connection );
            }
            if (resultSet != null ){
                logger.info ("查询成功！" );
            }
        } catch (SQLException e) {
            logger.error ("数据库查询异常！" );
            e.printStackTrace ();
        }

        return resultSet;
    }

    /**
     * 数据库更改 ， 返回成功状态
     * @param sql
     * @return
     */
    public boolean update( String sql ){
        Statement statement = null ;
        try {
            if ( connection != null ){
                statement = connection.createStatement ();
                logger.info ( "sql : " + sql );
                statement.executeUpdate ( sql );
                logger.info ("更改数据库成功！" );
            }else {
                logger.error ("connection is " + connection );
            }

        } catch (SQLException e) {
            logger.info ("更改数据库失败！" );
            e.printStackTrace ();
            return false;
        }
        return true;
    }
}
